<?php

namespace App\Miya\Tools;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class FalsifyCheckTool
{
    protected $refresh_ttl;

    public function __construct()
    {
        $this->refresh_ttl = config('allow.refresh_ttl');
    }

    public function check()
    {
        $cacheKey = 'falsify_check';
        if (Cache::has($cacheKey)) {
            return true;
        }
        $hash = md5($this->getFileContent(['../app', '../config', '../routes']));
        if ($hash == trim(Storage::get('hash.h'))) {
            Cache::add($cacheKey, true, $this->refresh_ttl);
            return true;
        } else {
            return false;
        }
    }

    public function getFileContent($dirs, &$content = '')
    {
        foreach ($dirs as $dir) {
            $structures = glob($dir . '/*');
            foreach ($structures as $structure) {
                if (strpos($structure, 'Console') !== false) {
                    continue;
                }
                if (strpos($structure, 'miya.php') !== false) {
                    continue;
                }

                if (is_dir($structure)) {
                    $this->getFileContent([$structure], $content);
                }

                if (is_file($structure)) {
                    $content .= file_get_contents($structure);
                }
            }
        }
        return $content;
    }
}
